﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AppManagement.BusManagers
{
    #region Using
    using DevComponents.DotNetBar;
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.Helpers;
    #endregion

    /// <summary>
    ///  manage chuc nang corresponding with menus in app
    /// </summary>
    public partial class FrmQuanLyChiSo : Office2007Form
    {
        //  event handler to transfer data to other forms
        public EventHandler Handler { get; set; }
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaDVCS;
        // ---------------- E -----------------

        public FrmQuanLyChiSo(bool EnableBtnChon = false)
        {
            InitializeComponent();
            InitHiddenFields();
            btnChon.Enabled = EnableBtnChon;
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaDVCS = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaDVCS",
                Text = ""
            };
            txtMaDVCS.Visible = false;
        }

        private void FrmQuanLyChiSo_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
            {
                MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionAdd())
            {
                LoadData();
                EraseTextboxes();
                MessageBoxEx.Show("Lưu dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBoxEx.Show("Lưu dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
            {
                MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBoxEx.Show("Bạn có chắc chắn xóa dòng này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ActionDelete())
                {
                    LoadData();
                    EraseTextboxes();
                    MessageBoxEx.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBoxEx.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
            {
                MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionUpdate())
            {
                LoadData();
                MessageBoxEx.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBoxEx.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            EraseTextboxes();
        }

        private void dtgvChiSo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;

            txtMaChiSo.Text = dtgvDataList.SelectedRows[0].Cells["MaCS"].Value.ToString(); ;

            var item = ChiSoRepository.SelectByID(txtMaChiSo.Text);
            LoadDetailInfo(item);
            
        }

        public void LoadDetailInfo(ChiSo item)
        {
            txtTenChiSo.Text = item.TenCS == null ? "" : item.TenCS;
            txtGhiChu.Text = item.GhiChu == null ? "" : item.GhiChu;
            txtMaDVCS.Text = item.MaDVCS == null ? "" : item.MaDVCS.ToString();
            txtDVCS.Text = item.MaDVCS == null ? "" : item.DonViChiSo.TenDVCS;
        }
        /// <summary>
        /// Load data from DB
        /// </summary>
        private void LoadData()
        {
            var lstItem = ChiSoRepository.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("MaCS");
            dt.Columns.Add("TenCS");
            dt.Columns.Add("TenDVCS");
            dt.Columns.Add("GhiChu");
            
            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaCS, lstItem[i].TenCS, lstItem[i].DonViChiSo.TenDVCS, lstItem[i].GhiChu);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
        {
            // Mode update -> checking MaChiSo is exists on textbox
            if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE)
            {
                if (txtMaChiSo.Text == "")
                {
                    errorText = "Vui lòng chọn chỉ số";
                    return false;
                }
            }
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtTenChiSo.Text == "")
                {
                    errorText = "Vui lòng nhập tên chỉ số";
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var item = new ChiSo
                {
                    MaCS = txtMaChiSo.Text,
                    TenCS = txtTenChiSo.Text,
                    GhiChu = txtGhiChu.Text
                };

                UpdateForeignKeys(item);

                if (!ChiSoRepository.Insert(item))
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Update item with specificed ID
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = ChiSoRepository.SelectByID(txtMaChiSo.Text);
                item.TenCS = txtTenChiSo.Text;
                item.GhiChu = txtGhiChu.Text;

                UpdateForeignKeys(item);

                return ChiSoRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        public void UpdateForeignKeys(ChiSo item)
        {
            if (txtMaDVCS.Text != "")
            {
                item.MaDVCS = int.Parse(txtMaDVCS.Text);
            }
        }

        /// <summary>
        /// Delete item with specified ID
        /// </summary>
        /// <returns></returns>
        private bool ActionDelete()
        {
            try
            {
                return ChiSoRepository.Delete(txtMaChiSo.Text);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtMaChiSo.Text = "";
            txtTenChiSo.Text = "";
            dtgvDataList.ClearSelection();
        }

        private void btnChonDVCS_Click(object sender, EventArgs e)
        {
            FrmQuanLyDonViChiSo frm = new FrmQuanLyDonViChiSo(true);
            frm.Handler += GetDVCS;
            frm.ShowDialog();
        }

        public void GetDVCS(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaDVCS.Text = comp[0];
            txtDVCS.Text = comp[1];
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.CHOOSING, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var id = txtMaChiSo.Text;
            var chiso = ChiSoRepository.SelectByID(id);
            TransferDataInfo(this, new TransferSimpleDataEvent(id + "#" + chiso.TenCS));
        }

        /// <summary>
        ///  function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, TransferSimpleDataEvent e)
        {
            this.Close();
            this.Handler(this, e);
        }
    }
}